<template>
  <div class="user-management-container">
    <el-row :gutter="20">
      <!-- 左侧部门树 -->
      <el-col :span="8">
        <el-card>
          <h3>部门</h3>
          <common-tree
              code="department"
              :treeProps="{ label: 'label', children: 'children' }"
              @node-click="handleDepartmentClick"
          ></common-tree>
        </el-card>
      </el-col>

      <!-- 右侧用户表格 -->
      <el-col :span="16">
        <el-card>
          <div class="table-header">
            <h3>人员管理</h3>
            <el-button type="primary" @click="openAddUserDialog">添加用户</el-button>
          </div>
          <common-table
              :fields="fields"
              :tableData="users"
              @edit="editUser"
              @delete="deleteUser"
          >
            <!-- 自定义渲染列 -->
            <template #role="{ row }">
              <span v-if="row.role === 'admin'">管理员</span>
              <span v-else>用户</span>
            </template>
          </common-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/编辑用户弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="currentUser" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="currentUser.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentUser.email"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="currentUser.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="用户" value="user"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CommonTree from '@/components/CommonTree.vue'; // 部门树形组件
import CommonTable from '@/components/CommonTable.vue'; // 通用表格组件

export default {
  components: {
    CommonTree,
    CommonTable,
  },
  data() {
    return {
      fields: [
        { prop: 'name', label: '姓名', width: '150' },
        { prop: 'email', label: '邮箱', width: '200' },
        { prop: 'role', label: '角色', width: '100' },
      ], // 表格字段配置
      users: [], // 当前部门下的用户数据
      currentUser: {
        id: null,
        name: '',
        email: '',
        role: '',
      }, // 当前编辑的用户信息
      dialogVisible: false, // 添加/编辑用户弹窗的可见性
      dialogTitle: '', // 弹窗标题
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
        ],
        role: [{ required: true, message: '请选择角色', trigger: 'change' }],
      },
    };
  },
  methods: {
    // 处理部门点击事件，加载部门下的用户
    handleDepartmentClick(node) {
      this.loadUsersByDepartment(node.id);
    },

    // 加载部门下的用户数据（模拟）
    loadUsersByDepartment(departmentId) {
      if (departmentId === 2) {
        this.users = [
          { id: 1, name: '张三', email: 'zhangsan@example.com', role: 'admin' },
          { id: 2, name: '李四', email: 'lisi@example.com', role: 'user' },
        ];
      } else if (departmentId === 3) {
        this.users = [
          { id: 3, name: '王五', email: 'wangwu@example.com', role: 'user' },
        ];
      } else {
        this.users = [];
      }
    },

    // 打开添加用户弹窗
    openAddUserDialog() {
      this.dialogTitle = '添加用户';
      this.dialogVisible = true;
      this.currentUser = { id: null, name: '', email: '', role: '' };
    },

    // 打开编辑用户弹窗
    editUser(user) {
      this.dialogTitle = '编辑用户';
      this.dialogVisible = true;
      this.currentUser = { ...user };
    },

    // 保存用户信息
    handleSaveUser() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          if (this.currentUser.id) {
            // 更新用户
            const index = this.users.findIndex((user) => user.id === this.currentUser.id);
            if (index !== -1) {
              this.users.splice(index, 1, { ...this.currentUser });
            }
          } else {
            // 添加用户
            this.currentUser.id = this.users.length + 1; // 模拟ID自增
            this.users.push({ ...this.currentUser });
          }
          this.dialogVisible = false;
          this.$message.success('用户保存成功');
        }
      });
    },

    // 删除用户
    deleteUser(user) {
      this.$confirm('确认删除此用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const index = this.users.findIndex((u) => u.id === user.id);
        if (index !== -1) {
          this.users.splice(index, 1);
        }
        this.$message.success('用户删除成功');
      });
    },
  },
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.el-col {
  padding: 10px;
}
</style>
